import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class PostUpdateServlet extends HttpServlet {
	private Connection connection;
	private Session session;
	private Topic requestTopic;
	
	private MessageConsumer consumer;

	@Override
	public void init() throws ServletException {
		try {
			Properties properties = new Properties();
			properties.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jnp.interfaces.NamingContextFactory");
			properties.put(Context.URL_PKG_PREFIXES, "org.jnp.interfaces");
			properties.put(Context.PROVIDER_URL, "localhost");

			InitialContext jndi = new InitialContext(properties);
			ConnectionFactory conFactory = (ConnectionFactory) jndi
					.lookup("XAConnectionFactory");
			connection = conFactory.createConnection();

			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			requestTopic = (Topic) jndi.lookup("topic/arsTopic");

			connection.start();

		} catch (NamingException NE) {
			System.out.println("Naming Exception: " + NE);
		} catch (Exception JMSE) {
			System.out.println("JMS Exception: " + JMSE);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		try{
			MessageProducer producer = session.createProducer(requestTopic);
			MapMessage mapParameters = session.createMapMessage();
			System.out.println("Posting message");
			mapParameters.setString("message", req.getParameter("message"));
			mapParameters.setLong("flightId", Long.parseLong(req.getParameter("flightId")));
			mapParameters.setString("journeyDate", req.getParameter("journeyDate"));
			
			producer.send(mapParameters);
			//producer.close();
			PrintWriter out = resp.getWriter();
			out.print("Flight update has been posted!");
			
		}catch(JMSException jmx){
			jmx.printStackTrace();
		}
	}
	
	
}


